<template>
  <view>
    <view class="search-box">
      <!-- uni-ui提供的搜索组件 -->
      <uni-search-bar @input="input" radius="100" bgColor="#ffffff" cancelButton="none" :focus="true">
      </uni-search-bar>
    </view>

    <!-- 搜索建议列表 -->
    <view class="sugg-list" v-if="kw.lenght !== 0 & searchResults.length !== 0">
      <view class="sugg-item" v-for="(item,i) in searchResults" :key="i" @click="gotoDetail(item.goods_id)">
        <view class="goods-name">{{item.goods_name}}</view>
        <uni-icons type="arrowright" size="16"></uni-icons>
      </view>
    </view>

    <!-- 搜索历史 -->
    <view class="history-box" v-else>
      <view class="history-title">
        <text>搜索历史</text>
        <uni-icons type="trash" size="17" @click="cleanHistory"></uni-icons>
      </view>
      <view class="history-list">
        <uni-tag :inverted="true" :text="item" v-for="(item,i) in histories" :key="i"
        @click="gotoGoodsList(item)">
        </uni-tag>
      </view>
    </view>

  </view>
</template>

<script>
  export default {
    data() {
      return {
        timer: null,
        kw: '',
        searchResults: [],
        historyList: []
      };
    },
    onLoad() {
      //从本地存储仓库中 获取键为'kw'的数据
      //JSON.parse()方法将字符串转换为数组
      this.historyList = JSON.parse(uni.getStorageSync('kw') || '[]')
    },
    methods: {
      //输入框防抖
      input(e) {
        clearTimeout(this.timer)
        this.timer = setTimeout(() => {
          this.kw = e
          // console.log(this.kw)
          this.getSearchList()
        }, 500)
      },
      //获取搜索建议列表
      async getSearchList() {
        //判断关键词是否为空
        if (this.kw === '') {
          this.searchResults = []
          return
        }
        ///发起请求，获取搜索建议列表
        const {
          data: res
        } = await uni.$http.get('/api/public/v1/goods/qsearch', {
          query: this.kw
        })
        this.searchResults = res.message
        
        //查询到搜索建之后，调用saveSearchHistory()方法保存搜索关键词
        this.saveSearchHistory()
      },
      
      gotoDetail(goods_id) {
        uni.navigateTo({
          url: '/subpkg/goods_detail/goods_detail?goods_id=' + goods_id
        })
      },
      //保存搜索关键词的一个自定义的方法
      saveSearchHistory(){
        //把搜索关键词push到historyList数组中
        // this.historyList.unshift(this.kw)
        this.historyList.push(this.kw)
        //调用uni.setStorageSync(key,value)将搜索历史记录持久化存储到本地 
        //  'kw'为键  JSON.stringify()可将数组转换成字符串
        uni.setStorageSync('kw',JSON.stringify(this.historyList))
      },
      //清空搜索历史
      cleanHistory(){
        //清空data中保存的搜索历史 即时不显示
        this.historyList = []
        //清空本地存储中记录的搜索历史 下次再加载搜索页时也不显示
        uni.setStorageSync('kw','[]')
      },
      gotoGoodsList(kw){
        uni.navigateTo({
          url:'/subpkg/goods_list/goods_list?query=' + kw
        })
      }
    },
    computed:{
      histories(){
        //数组中所有元素排序反转
        const arr = [...this.historyList].reverse()
        //数组元素去重
        return [...new Set(arr)]
      }
    }
  }
</script>

<style lang="scss">
  .search-box {
    position: sticky;
    top: 0;
    z-index: 999;
  }

  .sugg-list {
    padding: 0 5px;

    .sugg-item {
      font-size: 12px;
      padding: 13px 0;
      display: flex;
      border-bottom: 1px solid #efefef;
      align-items: center;
      justify-content: space-between;

      .goods-name {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }

  .history-box {
    padding: 0 10px;

    .history-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 40px;
      font-size: 13px;
      border-bottom: 1px solid #efefef;
    }

    .history-list {
      .uni-tag {
        margin-top: 5px;
        margin-right: 5px;
      }
    }
  }
</style>
